require_relative 'xml_helpers'

module CSDNConfig

	# helper for building the command script
	class Command
		include XMLHelpers

		def initialize
			@cmd = []
			yield self if block_given?
		end

		def add(*strs)
			@cmd += strs
		end

		def standard_build_setup
			prepare
		end
		
		def jdk7_setup
			add "export JAVA_HOME=$JAVA7_HOME"
			add "export PATH=$JAVA_HOME/bin:$PATH"
			add "java -version"
		end

		def clean_build_directory(name='target')
			remove_directory_if_exists name
		end

		def remove_directory_if_exists(name)
			add "if [ -d #{name} ]; then",
				"  rm -rf #{name}",
				"fi",
				""
		end

		def create_directory_and_change_to(name)
			add "mkdir #{name}; pushd $_"
		end

		def checkout_tag(sourceDir, tagFile='$WORKSPACE/jenkins_build.txt')
			add "build=`cat #{tagFile}`",
				'tag=jenkins-$build',
				"pushd #{sourceDir}",
				'git checkout $tag',
				'popd',
				''
		end

		def save_build_number(file='$WORKSPACE/jenkins_build.txt')
			add "echo $BUILD_NUMBER > #{file}"
		end


		def make(args=nil)
			add "mvn clean install"
		end
		
		def make_wo_test
			add "mvn clean install -Dmaven.test.skip=true"
		end
		
		def package
			add "mvn package"
		end
		
		def package_wo_test
			add "mvn package -Dmaven.test.skip=true"
		end
		
		def deploy
			add "mvn deploy"
		end
		
		def deploy_wo_test
			add "mvn deploy -Dmaven.test.skip=true"
		end

		def cd(newdir)
			add "cd #{newdir}"
		end

		def pushd(newdir)
			add "pushd #{newdir}"
		end

		def popd
			add "popd"
		end

		def gcovr_coverage_report(sourceDir, buildDir, exclude='.*UnitTests.*', reportFile='coverage_report.xml')
			add %Q|gcovr --xml-pretty -r #{sourceDir} --object-directory=#{buildDir} -e "#{exclude}" -o #{reportFile}|,
				 ''
		end

		def puts
			add ''
		end

		def prepare
			add "#!/bin/bash --login"
			add "export PATH=$MAVEN_HOME/bin:$SCALA_HOME/bin:$PATH"
			add "mvn -version"
			add "scala -version"
			add "cd src"
			add "git config user.email zhengwx@csdn.net"
			add "git config user.name wenxzhen"
		end

		def to_s
			@cmd * "\n"
		end
	end

end
